package mark.tom.gear.base.utils

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData

/**
 * @Description: LiveData 工具类
 * @Author: ttmk110@163.com
 * @Package: mark.tom.gear.base.utils
 * @Date: 2021/4/2
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date:
 * </ModifyLog>
 */
object LiveDataUtil {
    private var sMainHandler: Handler? = null

    /**
     * 用 setValue 更新 MutableLiveData 的数据，如果在子线程，就切换到主线程
     */
    fun <T> setValue(mld: MutableLiveData<T>?, d: T) {
        if (mld == null) {
            return
        }
        postSetValue(mld, d)
    }

    /**
     * 向主线程的 handler 抛 SetValueRunnable
     */
    private fun <T> postSetValue(mld: MutableLiveData<T>, d: T) {
        if (sMainHandler == null) {
            sMainHandler = Handler(Looper.getMainLooper())
        }
        sMainHandler!!.post(SetValueRunnable.create(mld, d))
    }

    private class SetValueRunnable<T> private constructor(
        private val liveData: MutableLiveData<T>,
        private val data: T
    ) : Runnable {
        override fun run() {
            liveData.value = data
        }

        companion object {
            fun <T> create(liveData: MutableLiveData<T>, data: T): SetValueRunnable<T> {
                return SetValueRunnable(liveData, data)
            }
        }
    }
}